//外接询价单编辑/详情

interface ICspInquiryEditViewModel extends ng.IScope {
    /**
     * 编辑询价发布是否隐藏
     */
    saveDis: boolean;
    /**
     * 总询价是否可以改动
     */
    editInquiryDis: boolean;
    /**
     * 标题
     */
    inquiryName: string;
    /** 
      * 询价单主键
     */
    id: string;
    /**
     * 子询价单编号
     */
    cspInquiryChildCode: string;
    /** 
    * Csp询价单总单编号
   */
    cspInquiryId: string;
    /**
     * 紧急程度
     */
    responseTime: string;
    /** 
    * 紧急程度单位
   */
    responseTimeUnit: string;
    /**
    *紧急程度单位下拉
    */
    urgencyUnitDropDown: ValueListItemResponse[];
    /**
     * 询价时间
     */
    cspInquiryTime: string;
    /**
     * 客户单位
     */
    clientName: string;
    /**
     * 发货计划人
     */
    customerName: string;
    /**
     * 发货人电话
     */
    customerPhone: string;
    /**总询价内容
     * 
     */
    content: string;
    /**
     * 目的地省
     */
    destinationProvince: string;
    /**
     * 目的地市
     */
    destinationCity: string;
    /**
     * 目的地区
     */
    destinationCounty: string;
    /**
     * 目的地详情
     */
    destinationDetails: string;
    /**
     * 起始省
     */
    originProvince: string;
    /** 
     * 起始市
    */
    originCity: string;
    /** 
     * 起始区
    */
    originCounty: string;
    /** 
     * 起始地详情
    */
    originDetails: string;
    /** 
     * 预计发货时间
    */
    foreArrivalTime: string;
    /** 
     * 预计到货时间
    */
    foreDeliveryTime: string;
    /**
    *公里数
   */
    mileage: number;
    /** 
     * 货物类别名称
    */
    goodsTypeName: string;
    /** 
     * 货物名称
    */
    goodsName: string;
    /** 
     * 货物数量
    */
    quantityOfGoods: number;
    /** 
     * 货物数量单位
    */
    goodsUnit: string;
    /** 
     * 所需车型
    */
    vehicleType: string;
    /** 
     * 所需车长
    */
    carLength: string;
    /** 
     * 承运方式
    */
    carriageWay: string;
    /** 
     * 装车效果
    */
    loadingEffect: string;
    /**
     * 附件备注 */
    attachmentRemarks: string;
    /**
     * 附件列表
     */
    attachmentList: Array<AttachmentDetail>;
    /**
    * 商务专员id
    */
    businessOfficerId: string;
    /**
     * 商务专员
     */
    businessOfficerName: string;
    /**
     * 商务专员下拉列表
     */
    businessOfficerDropDown: EmployeeListItemResponse[];
    /**
    *客服专员编号
    */
    customerServiceOfficerId: string;
    /**
     * 客服专员
     */
    customerServiceOfficerName: string;
    /**
     * 客服专员下拉列表
     */
    serviceOfficerIdDropDown: EmployeeListItemResponse[];
    /**
    *调度专员编号
    */
    dispatchOfficerId: string;
    /**
     * 调度专员
     */
    dispatchOfficerName: string;
    /**
     *调度专员下拉列表
     */
    dispatchOfficerDropDown: EmployeeListItemResponse[];
    /**
     * 计划专员
     */
    plannerName: string;
    /**
     * 客户单位编号
     */
    clientId: string;
    /**
     * 发货计划人编号
     */
    consignorId: string;
    /**
     *发货地省下拉
    */
    startProvinceDropDown: Array<AreaItem>;
    /**
     *发货地市下拉
     */
    startCityDropDown: Array<AreaItem>;
    /**
     *发货地区下拉
    */
    startAreaDropDown: Array<AreaItem>;
    /**
     *送货地省下拉
    */
    endProvinceDropDown: Array<AreaItem>;
    /**
     *送货地市下拉
    */
    endCityDropDown: Array<AreaItem>;
    /**
     *送货地区下拉
    */
    endAreaDropDown: Array<AreaItem>;
    /**
     *货物类别编号
    */
    goodsTypeId: string;
    /**
     *货物类别下拉
    */
    goodsTypeDropDown: Array<GoodsTypeListItemResponse>;
    /**
     *货物编号
    */
    goodsId: string;
    /**
     *货物名称下拉
    */
    goodsNameDropDown: Array<GoodsListItemResponse>;
    /**
    *货物数量
   */
    goodsQuantity: number;
    /**
     *货物数量单位下拉
    */
    goodsQuantityUnitDropDown: ValueListItemResponse[];
    /**
     *所需车型下拉
    */
    carTypeDropDown: ValueListItemResponse[];
    /**
     *所需车长下拉
    */
    carLengthDropDown: ValueListItemResponse[];
    /**
     *承运方式下拉
    */
    carrierCategoryDropDown: ValueListItemResponse[];
    /**
    * 附件上传组件
     */
    attachmentUploader: any;
    /**
     * 客户自动补全
     */
    searchClient: (value: string) => any;
    /**
     * 选择客户单位事件
     */
    clientSelect: (selected: angucomplete<ClientListItemResponse>) => void;
    /**
     * 发货计划人补全事件
     */
    searchConsignor: (value: string) => void;
    /**
     * 货物事件
     */
    goodsTypeSelect: () => void;
    /**
     * 选择发货计划人事件
     */
    consignorSelect: (selected: angucomplete<CustomerRepresentativeListItemResponse>) => void;
    /**
     *编辑询价发布
     */
    cspinquirySaveEdit: () => void;
    /**
     * 货物名称自动补全事件
     */
    onGoodsNameAutoComplate: (value: string) => any;
    /**
     * 货物名称选中事件
     */
    onGoodsNameSelected: (selected: angucomplete<GoodsListItemResponse>) => void;
}

class CspInquiryEditController {

    uploaderList: Array<attachmentList>;
    baseImageUrl: string;
    /**
     * 询价单类型
     */
    name: string;
    cspinquiryId: string;
    /**
  * 子询价单列表数据
  */
    inquiryChildListData: Array<InquiryChildListResponse>;

    constructor(private $scope: ICspInquiryEditViewModel,
        private customerRepresentativeService: ICustomerRepresentativeService,
        private $state: angular.ui.IStateService,
        private $location: ng.ILocationService,
        private $http: ng.IHttpService,
        private cspInquiryService: ICspInquiryService,
        private inquiryService: IInquiryService,
        private clientService: IClientService,
        private employeeService: IEmployeeService,
        private goodsService: IGoodsService,
        private goodsTypeService: IGoodsTypeService,
        private areaService: IAreaService,
        private valueService: IValueService,
        private routeService: routeService,
        private $stateParams: any,
        private $ngBootbox: BootboxService,
        private commonService: ICommonService, 
        private $q: ng.IQService,
        private ossUploaderService:ossUploaderService
        ) {
        this.baseImageUrl = this.routeService.getBaseUrl() + "attachment/";
        this.uploaderList = [];
        this.init();
    }

    init(): void {
        this.name = this.$location.search().name;
        // alert(this.name)
        this.cspinquiryId = this.$location.search().id;
        this.inquiryChildListData = [];

        /** 
         * 计划专员取当前登录人员
        */
        if (window.localStorage.getItem("loginData").toString()) {
            this.$scope.plannerName = JSON.parse(window.localStorage.getItem("loginData").toString()).realName;
        };

        this.$scope.editInquiryDis = false;
        this.$scope.inquiryName = "外接询价单编辑新增";
        this.$scope.cspinquirySaveEdit = this.cspinquirySaveEdit;
        /**
         * 自动补全事件
         */
        this.$scope.searchClient = this.searchClient;
        this.$scope.searchConsignor = this.searchConsignor;
        this.$scope.onGoodsNameAutoComplate = this.onGoodsNameAutoComplate;
        this.$scope.onGoodsNameSelected = this.onGoodsNameSelected;

        /**
         * 选择事件
         */
        this.$scope.clientSelect = this.clientSelect;
        this.$scope.goodsTypeSelect = this.goodsTypeSelect;
        this.$scope.consignorSelect = this.consignorSelect;

        this.loadBusinessOfficerDropDown();
        this.loadServiceOfficerIdDropDown();
        this.loadDispatchOfficerDropDown();
        this.loadUrgencyUnitDropDown();
        this.loadGoodsQuantityUnitDropDown();
        this.loadCarTypeDropDown();
        this.loadCarLengthDropDown();
        this.loadCarrierCategoryDropDown();
        $('#opendataTime').click(() => {
            $('#dataTime').datetimepicker('show');
        });

        $('#opendataTimeEnd').click(() => {
            $('#dataTimeEnd').datetimepicker('show');
        });

        if (this.cspinquiryId != null) {
            this.cspInquiryService.getDetail(this.cspinquiryId).then(res => {
                this.$scope.id = res.data.id;
                this.$scope.cspInquiryChildCode = res.data.cspInquiryChildCode;
                this.$scope.cspInquiryId = res.data.cspInquiryId;
                this.$scope.responseTime = String(res.data.responseTime);
                this.$scope.responseTimeUnit = res.data.responseTimeUnit;
                this.$scope.cspInquiryTime = res.data.cspInquiryTime;
                this.$scope.clientId = res.data.clientId;
                this.$scope.consignorId = res.data.consignorId;
                this.$scope.clientName = res.data.clientName;
                this.$scope.customerName = res.data.customerName;
                this.$scope.customerPhone = res.data.customerPhone;
                this.$scope.content = res.data.content;
                this.$scope.originProvince = res.data.originProvince;
                this.$scope.originCity = res.data.originCity;
                this.$scope.originCounty = res.data.originCounty;
                this.$scope.originDetails = res.data.originDetails;
                this.$scope.foreArrivalTime = res.data.foreArrivalTime;
                this.$scope.destinationProvince = res.data.destinationProvince;
                this.$scope.destinationCity = res.data.destinationCity;
                this.$scope.destinationCounty = res.data.destinationCounty;
                this.$scope.destinationDetails = res.data.destinationDetails;
                this.$scope.foreDeliveryTime = res.data.foreDeliveryTime;
                this.$scope.goodsTypeId = res.data.goodsTypeId;
                this.$scope.goodsId = res.data.goodsId;
                this.$scope.goodsName = res.data.goodsName;
                this.$scope.quantityOfGoods = res.data.quantityOfGoods;
                this.$scope.goodsUnit = res.data.goodsUnit;
                this.$scope.vehicleType = res.data.vehicleType;
                this.$scope.carLength = res.data.carLength;
                this.$scope.carriageWay = res.data.carriageWay;
                this.$scope.loadingEffect = res.data.loadingEffect;
                this.$scope.attachmentRemarks = res.data.attachmentRemarks;

                this.goodsTypeDropDown();
                // this.loadGoodsDropDown(this.$scope.goodsTypeId);

                /**
                 * 附件信息(编辑显示)
                 */
                // if (res.data.attachmentList.length <= 0) {
                //     // return;
                // }
                if(res.data.attachmentList.length>0) {
                    // res.data.attachment.forEach((item, index) => {
                    //     this.uploaderList.push(item);
                    //     this.showFileItem(item, this.$scope.attachmentUploader);
                    // });
                    res.data.attachmentList.forEach((item, index) => {
                        this.uploaderList.push({
                            attachmentId: item.attachmentId,
                            attachmentName: item.attachmentName,
                            attachmentPath: item.attachmentPath,
                            attachmentTag: item.attachmentTag,
                        });
                        
                        this.$scope.attachmentUploader.addByPath(item.attachmentPath,{id:item.attachmentId,name:item.attachmentName})
                        // this.commonService.showFileItem({
                        //     attachmentId: item.attachmentId,
                        //     attachmentName: item.attachmentName,
                        //     attachmentPath: item.attachmentPath,
                        //     attachmentTag: item.attachmentTag,
                        // }, this.$scope.attachmentUploader);
                    });
                }

                /**
             * 查看详情
             */
            console.log('name',this.name)
                if (this.name == "detail") {
                    // alert('!!!')
                    $(".province").attr("disabled", "disabled");
                    $(".city").attr("disabled", "disabled");
                    $(".area").attr("disabled", "disabled");
                    this.$scope.editInquiryDis = true;
                    this.$scope.inquiryName = "外接询价单详情";
                }
            });

        }

       
        
        const OssFile = this.ossUploaderService.getOssFile();
        this.$scope.attachmentUploader= new OssFile(this.$scope,this.$scope.attachmentUploader,{uploaderList:this.uploaderList,tag:1,multiple:true});
        this.$scope.attachmentUploader.onSuccess=(it)=>{
            console.log('onsuccess',it);
            this.onSuccessItem(it.fileId, it.fileName,it.imgSrc,1,it._file)

        }

    }

    /**
     * 客户单位自动补全
     */
    searchClient = (value: string) => {
        return this.clientService.getList(value, "","", "", "", "", 0, 5).then((res) => {
            return res.data.data;
        });
    }

    /**
     * 选择客户单位
     */
    clientSelect = (selected: angucomplete<ClientListItemResponse>) => {
        if (selected) {
            this.$scope.clientId = selected.description.id;
            this.$scope.goodsTypeId = "";
            this.$scope.goodsTypeDropDown = [];
            this.$scope.goodsId = "";
            this.$scope.goodsNameDropDown = [];
            this.goodsTypeDropDown();
            this.$scope.$broadcast('angucomplete-alt:clearInput', 'goodsId');

        }
    }
    /**
     * 发货计划人补全事件
     */
    searchConsignor = (value: string) => {
        return this.customerRepresentativeService.getList(this.$scope.clientId, value, "", 0, 5).then(res => {
            return res.data.data;
        })
    }

    /**
     * 选择发货计划人事件
     */
    consignorSelect = (selected: angucomplete<CustomerRepresentativeListItemResponse>) => {
        if (selected) {
            this.$scope.consignorId = selected.description.id;
            this.$scope.customerPhone = selected.description.phoneNumber;
        }
    }
    /**
     * 获取货物类别下拉
     */
    goodsTypeDropDown = () => {
        this.goodsTypeService.getList(this.$scope.clientId, "", 0, -1).then((res) => {
            this.$scope.goodsTypeDropDown = res.data.data;
            if (this.$scope.clientId == undefined || this.$scope.clientId == "") {
                this.$scope.goodsTypeDropDown = [];
                this.$scope.goodsTypeId = "";
            }
        });
    }

    /**
     * 选择货物类型事件
     */
    goodsTypeSelect = () => {
        // this.loadGoodsDropDown(this.$scope.goodsTypeId);
        this.$scope.$broadcast('angucomplete-alt:clearInput', 'goodsId');
    }
    /**
     * 获取货物名称下拉
     */
    // loadGoodsDropDown = (goodsTypeId:string) => {
    //     this.goodsService.getList(this.$scope.clientId, "",goodsTypeId, 0, -1).then(result => {
    //         this.$scope.goodsNameDropDown = result.data.data;
    //         if (this.$scope.goodsTypeId == undefined || this.$scope.goodsTypeId == ""){
    //             this.$scope.goodsNameDropDown = [];
    //             this.$scope.goodsId = "";
    //         };
    //     });
    // }
    /**
* 货物名称自动补全事件
*/
    onGoodsNameAutoComplate = (value: string) => {
        // console.log($("#goodsId_value").val());
        var deferred = this.$q.defer();
        if (!this.$scope.clientId || !this.$scope.goodsTypeId) {
            // deferred.resolve("well done!");
        } else {
            return this.goodsService.getList(this.$scope.clientId, value, this.$scope.goodsTypeId, 0, 30).then(res => {
                return res.data.data;
            })
        }
        return deferred.promise;
        //console.log(this.$q.reject)
    }

    /**
     * 货物名称选中事件
     */
    onGoodsNameSelected = (selected: angucomplete<GoodsListItemResponse>) => {
        if (selected) {
            this.$scope.goodsName = selected.description.name;
            this.$scope.goodsId = selected.description.id;
            $("#goodsId_value").val(selected.description.name);

        } else {
            this.$scope.goodsName = "";
            this.$scope.goodsId = "";
        }

    }

    /**
     * 编辑询价发布
     */
    cspinquirySaveEdit = () => {
        if (!$("#inquiryForm").valid()) {  this.$ngBootbox.alert('请填写正确！'); return };
        if (!this.commonService.timeJudge($("#dataTime").val(), $("#dataTimeEnd").val())) { return; };
        var attachmentArr = [];

        this.uploaderList.forEach((item, index) => {
            // attachmentArr.push([item.attachmentId,item.attachmentName,item.attachmentPath,item.attachmentTag]);   
            attachmentArr.push([item.attachmentName, item.attachmentPath]);

        });
        this.$ngBootbox.confirm("确认外接询价单发布吗？").then(() => {
            let inquiryChildListPractical = {
                startProvince: this.$scope.originProvince,
                startCity: this.$scope.originCity,
                startArea: this.$scope.originCounty,
                startAddress: this.$scope.originDetails,
                endProvince: this.$scope.destinationProvince,
                endCity: this.$scope.destinationCity,
                endArea: this.$scope.destinationCounty,
                endAddress: this.$scope.destinationDetails,
                plannedArrivalTime: $("#dataTime").val(),
                plannedDeliveryTime: $("#dataTimeEnd").val(),
                mileage: this.$scope.mileage,
                goodsTypeId: this.$scope.goodsTypeId,
                goodsTypeName: $("#inquiryAdd_goodsTypeName option:selected").text(),
                goodsId: this.$scope.goodsId,
                // goodsName: $("#inquiryAdd_goodsName option:selected").text(),
                goodsName: $("#goodsId_value").val(),
                goodsQuantity: this.$scope.quantityOfGoods,
                goodsQuantityUnit: this.$scope.goodsUnit,
                carType: this.$scope.vehicleType,
                carLength: this.$scope.carLength,
                carrierCategory: this.$scope.carriageWay,
                loadingEffect: this.$scope.loadingEffect,
                remarks: this.$scope.attachmentRemarks,
            };
            this.inquiryChildListData = [inquiryChildListPractical];

            this.clientService.getDetail(this.$scope.clientId).then((res) => {
                let clientCornet = res.data.cornet;
                this.inquiryService.add(
                    Number(this.$scope.responseTime),
                    this.$scope.responseTimeUnit,
                    this.$scope.businessOfficerId,
                    this.$scope.plannerName,
                    $("#inquiryAdd_businessOfficerId option:selected").text(),
                    this.$scope.customerServiceOfficerId,
                    $("#inquiryAdd_customerServiceOfficerId option:selected").text(),
                    this.$scope.dispatchOfficerId,
                    $("#inquiryAdd_dispatchOfficerId option:selected").text(),
                    this.$scope.clientId,
                    $("#client_value").val(),
                    this.$scope.consignorId,
                    this.$scope.content,
                    this.inquiryChildListData,
                    //this.uploaderList,
                    attachmentArr,
                    this.$scope.attachmentRemarks,
                    clientCornet,
                    this.cspinquiryId
                ).then((res) => {
                    if(this.$state.current.name.indexOf('New')>-1){
                        this.$state.go('app.inquiry.external_inquiryNew', { name: 'inquiry' });
                        
                    }else{
                        this.$state.go('app.inquiry.external_inquiry', { name: 'inquiry' });
                    }
                });
            });
        });

    }

    /**
    * 紧急程度单位下拉
    */
    loadUrgencyUnitDropDown = () => {
        this.$scope.urgencyUnitDropDown = this.valueService.getUrgencyUnitList().data;
    }
    /**
    * 商务专员下拉
    */
    loadBusinessOfficerDropDown = () => {
        this.employeeService.getbytype(CommissionerType.BusinessAffairs.toString(),  0, -1).then(result => {
            this.$scope.businessOfficerDropDown = result.data.data;
        });
    }

    /**
     * 客服专员下拉
     */
    loadServiceOfficerIdDropDown = () => {
        this.employeeService.getbytype(CommissionerType.CustomerService.toString(),  0, -1).then(result => {
            this.$scope.serviceOfficerIdDropDown = result.data.data;
        });
    }

    /**
     * 调度专员下拉
     */
    loadDispatchOfficerDropDown = () => {
        this.employeeService.getbytype(CommissionerType.Dispatch.toString(),  0, -1).then(result => {
            this.$scope.dispatchOfficerDropDown = result.data.data;
        });
    }
    /**
     * 货物数量单位下拉
     */
    loadGoodsQuantityUnitDropDown = () => {
        this.$scope.goodsQuantityUnitDropDown = this.valueService.getGoodQuantityUnitList().data;
    }

    /**
     * 车型下拉
     */
    loadCarTypeDropDown = () => {
        this.$scope.carTypeDropDown = this.valueService.getCarTypeList().data;
    }

    /**
     * 车长下拉
     */
    loadCarLengthDropDown = () => {
        this.$scope.carLengthDropDown = this.valueService.getCarLengthList().data;
    }

    /**
     * 承运方式下拉
     */
    loadCarrierCategoryDropDown = () => {
        this.$scope.carrierCategoryDropDown = this.valueService.getCarrierWayList().data;
    }

    /**
     * 选择上传文件后
     */
    onSuccessItem(fileId: string, fileName: string, filePath: string, tag: number, file?: any): void {
        file.fileId = filePath;
        let attachment = {
            attachmentId: fileId,
            attachmentName: fileName,
            attachmentPath: filePath,
            attachmentTag: ""
        };
        this.uploaderList.push(attachment);
    }


}

angular.module('tms').controller("cspinquiryEditController", ["$scope", "customerRepresentativeService", "$state", "$location", "$http", "cspInquiryService", "inquiryService", "clientService", "employeeService", "goodsService", "goodsTypeService", "areaService", "valueService", "routeService", "$stateParams", "$ngBootbox", "commonService", "$q","ossUploaderService", CspInquiryEditController]);